//
//  TransferredViewController.m
//  SP2P
//
//  Created by 吴建东 on 16/6/12.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "TransferredViewController.h"
#import "TransferredView.h"
#import "payLimitViewController.h"
#import "SetPayPasswordViewController.h"
#import "AddBankCardViewController.h"
#import "MakeSureToViewController.h"
#define ButtonNumber    2
@interface TransferredViewController ()<UIScrollViewDelegate,HTTPClientDelegate,TransferredViewDelegate>
{
    UIButton *_bankTransferredButton;
    UIButton *_amountTransferredButton;
    UIView   *_buttonView;
    UIView   *_buttonLineView;
    NSDictionary *_bankDict;
    TransferredView *bankView;
    TransferredView *accountView;
    BOOL _fy_onoff;
    BOOL _cj_onoff;
    
}
@property (weak, nonatomic) IBOutlet UIView *cutView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (nonatomic, strong) NetWorkClient *requestClient;
@property (nonatomic, assign) NSInteger     requestType;
@property (nonatomic, assign) BOOL          isLoading;
@end

@implementation TransferredViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self initNavBarTitle:@"转入" andLeftItemName:@"返回" andRightItemName:@"额度表"];
    
    [self initData];
    [self initView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addBankCardSuccess) name:@"addBankCardSuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(makeSureTransferred:) name:@"makeSureTransferred" object:nil];
}

- (void)addBankCardSuccess {
    [self requestData];
}
- (void)makeSureTransferred:(NSNotification *)notifi{
    MakeSureToViewController *msVC = [[MakeSureToViewController alloc] init];
    msVC.userBanksDict = _bankDict;
    msVC.viewType = [notifi.object  integerValue];
    if (msVC.viewType == 1) {
        msVC.amount = bankView.amountTextField.text;
        msVC.fy_onoff = _fy_onoff;
        msVC.cj_onoff = _cj_onoff;
        msVC.payView.fyBtn.hidden = !_fy_onoff;
        msVC.payView.cjBtn.hidden = !_cj_onoff;
        if (_fy_onoff == 0 && _cj_onoff == 1) {
            [msVC.payView.cjBtn setAutoresizingMask:UIViewAutoresizingNone];
            CGRect payframe = msVC.payView.backView.frame;
            payframe.size.height = msVC.payView.backView.frame.size.height-msVC.payView.fyBtn.frame.origin.y+msVC.payView.cjBtn.frame.origin.y;
            msVC.payView.backView.frame = payframe;
            CGRect cancelFrame = msVC.payView.cancelBtn.frame;
            cancelFrame.origin.y = GetMaxY(msVC.payView.backView)+KAdaptNum(20);
            msVC.payView.cancelBtn.frame = cancelFrame;
        } else if (_fy_onoff == 1 && _cj_onoff == 0) {
            [msVC.payView.fyBtn setAutoresizingMask:UIViewAutoresizingNone];
            [msVC.payView.cjBtn setAutoresizingMask:UIViewAutoresizingNone];
            
            CGRect payframe = msVC.payView.backView.frame;
            payframe.size.height = msVC.payView.backView.frame.size.height-msVC.payView.fyBtn.frame.origin.y+msVC.payView.cjBtn.frame.origin.y;
            
            msVC.payView.backView.frame = payframe;
            CGRect fyBtnFrame = msVC.payView.fyBtn.frame;
            fyBtnFrame.origin.y = msVC.payView.cjBtn.frame.origin.y;
            msVC.payView.fyBtn.frame = fyBtnFrame;
            CGRect cancelFrame = msVC.payView.cancelBtn.frame;
            cancelFrame.origin.y = GetMaxY(msVC.payView.backView)+KAdaptNum(20);
            msVC.payView.cancelBtn.frame = cancelFrame;
            
        }

    }else{
        msVC.amount = accountView.amountTextField.text;
        msVC.balance = accountView.balanceStr;
        
    }
    
    
    [self.navigationController pushViewController:msVC animated:YES];
}
#pragma mark -Delegate
- (void)transterredWithAmount:(double)amount type:(NSInteger)viewType {
    
}

- (void)gotoSetTradePassword {
    //设置交易密码
    SetPayPasswordViewController *setPayPassword = [[SetPayPasswordViewController alloc] init];
    //    changePwd.delegate = self;
    setPayPassword.editType = 1;
    [self.navigationController pushViewController:setPayPassword animated:YES];
}

- (void)gotoRealNameVerify {
    //去实名认证
    AddBankCardViewController *addBankCard = [[AddBankCardViewController alloc] init];
    addBankCard.editType = 1;
    [self.navigationController pushViewController:addBankCard animated:YES];
}

- (void)gotoBindCard {
    //去绑卡
    AddBankCardViewController *addBankCard = [[AddBankCardViewController alloc] init];
    addBankCard.editType = 1;
    [self.navigationController pushViewController:addBankCard animated:YES];
}



#pragma mark - Action
- (void)headerButtonClick:(UIButton *)button {
    if (button == _bankTransferredButton) {
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame = _buttonLineView.frame;
            frame.origin.x = 0;
            _buttonLineView.frame = frame;
            _scrollView.contentOffset = CGPointMake(0, 0);
        } completion:^(BOOL finished) {
            [self buttonChange:button];
        }];
    }else if(button == _amountTransferredButton){
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame = _buttonLineView.frame;
            frame.origin.x = MSWIDTH/ButtonNumber;
            _buttonLineView.frame = frame;
            _scrollView.contentOffset = CGPointMake(MSWIDTH, 0);
        } completion:^(BOOL finished) {
            [self buttonChange:button];
        }];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == _scrollView) {
        double OriginX = scrollView.contentOffset.x;
        if (OriginX>=0 && OriginX<=MSWIDTH) {
            CGRect frame = _buttonLineView.frame;
            frame.origin.x = (OriginX/MSWIDTH)*(MSWIDTH/ButtonNumber);
            _buttonLineView.frame = frame;
            
            if (OriginX <= MSWIDTH/2) {
                [self buttonChange:_bankTransferredButton];
            }else {
                [self buttonChange:_amountTransferredButton];
            }
        }else {
        }
    }
    
    [bankView keyboardHidden];
    [accountView keyboardHidden];
}

- (void)buttonChange:(UIButton *)button {
    if (button == _bankTransferredButton) {
        [_bankTransferredButton setTitleColor:KColor forState:UIControlStateNormal];
        _bankTransferredButton.titleLabel.font = KFontBoldSize(14.0);
        
        [_amountTransferredButton setTitleColor:KBlackColor forState:UIControlStateNormal];
        _amountTransferredButton.titleLabel.font = KFontSize(14.0);
       

    }else if (button == _amountTransferredButton) {
        [_bankTransferredButton setTitleColor:KBlackColor forState:UIControlStateNormal];
        _bankTransferredButton.titleLabel.font = KFontSize(14.0);
        
        [_amountTransferredButton setTitleColor:KColor forState:UIControlStateNormal];
        _amountTransferredButton.titleLabel.font = KFontBoldSize(14.0);
    }
}

#pragma mark - Data
- (void)initData {
    
    [self requestData];
}

- (void)requestData {
    _requestType = 1;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"502" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"userId"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}


- (void)startRequest {
    _isLoading = YES;
}

- (void)httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
    _isLoading = NO;
    NSDictionary *dics=(NSDictionary *)obj;
    DLOG(@"--%@",dics);
    
    NSString *errorStr=[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]];
    if ([errorStr isEqualToString:@"-1"]) {
        if (_requestType == 1) {
            NSString *balance = [NSString stringWithFormat:@"%@",[CommonClass formatConversion:[dics[@"balance"] doubleValue] type:1]];
            accountView.balanceStr = balance;
            _fy_onoff = [dics[@"fy_onoff"] boolValue];
            _cj_onoff = [dics[@"cj_onoff"] boolValue];
           
            NSArray *userBanks = dics[@"userBanks"];
            if (userBanks.count > 0) {
                _bankDict = userBanks[0];
                bankView.userBanksDict = _bankDict;
            }else {
                bankView.userBanksDict = nil;
            }
            }
        
        
    }else if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-2"]) {
        
        [ReLogin outTheTimeRelogin:self];
    }else {
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",[dics objectForKey:@"msg"]]];
    }
}

- (void)httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error {
    _isLoading = NO;
}

- (void) networkError {
    _isLoading = NO;
}

#pragma mark - View
- (void)initView {
    [self loadButtonView];
    
    _scrollView.frame = RECTMAKE(0, GetMaxY(_buttonView), MSWIDTH, MSHIGHT - 64 - GetMaxY(_buttonView));
    _scrollView.delegate = self;
    _scrollView.contentSize = CGSizeMake(MSWIDTH*2, 0);
    _scrollView.pagingEnabled = YES;
    //_scrollView.bounces = NO;
    
    NSArray *bankNib = [[NSBundle mainBundle] loadNibNamed:@"TransferredView" owner:self options:nil];
    bankView = [bankNib objectAtIndex:0];
    bankView.viewType = 1;
    bankView.delegate = self;
   
    bankView.frame = RECTMAKE(0, 0, MSWIDTH, GetHeight(_scrollView));
    [bankView loadView];
    [_scrollView addSubview:bankView];
    
    
    NSArray *accountNib = [[NSBundle mainBundle] loadNibNamed:@"TransferredView" owner:self options:nil];
    accountView = [accountNib objectAtIndex:0];
    accountView.viewType = 2;
    accountView.delegate = self;
    accountView.frame = RECTMAKE(MSWIDTH, 0, MSWIDTH, GetHeight(_scrollView));
    [accountView loadView];
    [_scrollView addSubview:accountView];


}

- (void)loadButtonView {
    
    CGFloat scrollOriginY = KAdaptNum(45);
    
    _buttonView = [UIView viewWithFrame:CGRectMake(0, 0, MSWIDTH, scrollOriginY) backgroundColor:[UIColor whiteColor] superview:self.view];
    
    _bankTransferredButton = [UIButton buttonWithFrame:CGRectMake(0, 0, MSWIDTH/ButtonNumber, scrollOriginY - 1) backgroundColor:nil title:@"网银转入" titleColor:KColor titleFont:14.0 target:self action:@selector(headerButtonClick:) superview:_buttonView];
    
    _amountTransferredButton = [UIButton buttonWithFrame:CGRectMake(MSWIDTH/ButtonNumber, 0, MSWIDTH/ButtonNumber, GetHeight(_bankTransferredButton)) backgroundColor:nil title:@"余额转入" titleColor:KBlackColor titleFont:14.0 target:self action:@selector(headerButtonClick:) superview:_buttonView];
    
    
    UIView *buttonLine = [UIView viewWithFrame:CGRectMake(0, CGRectGetMaxY(_bankTransferredButton.frame), MSWIDTH, _buttonView.frame.size.height - CGRectGetMaxY(_bankTransferredButton.frame)) backgroundColor:nil superview:_buttonView];
    
    _buttonLineView = [UIView viewWithFrame:CGRectMake(0, 0, MSWIDTH/ButtonNumber, GetHeight(buttonLine)) backgroundColor:KColor superview:buttonLine];
    
}

- (void)rightBarButtonClick {
    payLimitViewController *limitTable = [[payLimitViewController alloc] init];
    [self.navigationController pushViewController:limitTable animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
